package personal.vivian.web.controller;

import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import personal.vivian.entity.SysPermission;
import personal.vivian.entity.UserInfo;

import java.io.Serializable;
import java.util.concurrent.atomic.AtomicLong;

@Controller
public class LoginController {
    private AtomicLong accessCount=new AtomicLong(0);
    private long failCount=0L;
    @RequestMapping(name = "/ajaxLogin")
    @ResponseBody
    public String ajaxLogin(@RequestBody  UserInfo userInfo){
        long l = accessCount.addAndGet(1);
        System.out.println("count:"+l);
        JSONObject jsonObject=new JSONObject();
        Subject subject = new Subject.Builder().buildSubject();
        UsernamePasswordToken token=new UsernamePasswordToken(userInfo.getUserName(),userInfo.getPassword());
        try{
            subject.login(token);
            jsonObject.put("token",subject.getSession().getId());
            jsonObject.put("msg","登录成功");
            jsonObject.put("count",l);
        }catch (IncorrectCredentialsException ice){
            failCount++;
            jsonObject.put("msg","密码错误");
            jsonObject.put("count",failCount);
        }catch (LockedAccountException lae){
            jsonObject.put("msg","登录失败，该用户已被冻结");
        }catch (AuthenticationException ae){
            jsonObject.put("msg","该用户不存在");
        }catch (Exception e){
            e.printStackTrace();
        }

        return jsonObject.toString();
    }
}
